package handler

import (
	"github.com/gin-gonic/gin"
	"gorm-demo/model/request"
	"gorm-demo/service/role"
	"gorm-demo/utils/result"
	"log"
	"net/http"
	"strings"
	"time"
)

func RoleList(context *gin.Context) {
	context.JSON(200, result.New().SetData(role.GetRoles()).Success())
}

func BatchSaveRole(ctx *gin.Context) {
	var roles request.RoleRequest
	err := ctx.ShouldBindJSON(&roles)
	if err != nil {
		log.Default().Println(err)
		ctx.JSON(http.StatusInternalServerError, result.New().Fail().SetMsg("参数错误请重试"))
		return
	}
	role.AddRole(roles)
	ctx.JSON(200, result.New().Success())
}

func UpdateRoles(ctx *gin.Context) {
	var roles request.RoleRequest
	if err := ctx.ShouldBindJSON(&roles); err != nil {
		log.Default().Println(err)
		ctx.JSON(http.StatusInternalServerError, result.New().Fail().SetMsg("参数错误请重试"))
		return
	}
	err := role.UpdateRoles(roles)
	if err != nil {
		ctx.JSON(http.StatusBadRequest, result.New().Fail().SetMsg(err.Error()))
		return
	}
	ctx.JSON(200, result.New().Success())
}

func DeleteRole(ctx *gin.Context) {
	now := time.Now()
	roleIds := strings.Split(ctx.Param("roleIds"), ",")
	err := role.BatchDeleteRole(roleIds)
	if err != nil {
		ctx.JSON(http.StatusBadRequest, result.New().Fail().SetMsg("新增失败请重试"))
		return
	}
	log.Default().Println("删除角色耗时:", time.Since(now))
	ctx.JSON(200, result.New().Success())
}
